<?php

namespace app\v6\controller;

use think\facade\Lang;

class User
{
    /**
     * 用户信息.
     */
    public function info()
    {
        $result = [
            'code' => 1,
            'msg' => Lang::get('get_user_info_failed'),
            'data' => [],
        ];

        // 获取当前登录用户ID
        $userId = getUserId();
        if (empty($userId)) {
            $result['msg'] = Lang::get('user_not_logged_in');
            $result['code'] = 401;

            return json($result);
        }

        // 查询用户信息
        $userInfo = db('member')->where('id', $userId)->find();
        if (empty($userInfo)) {
            $result['msg'] = '用户不存在';

            return json($result);
        }

        // 格式化数据
        $data = [
            'id' => $userInfo['id'],
            'nickname' => ($userInfo['nickname'] ?: (empty($userInfo['phone']) ? $userInfo['email'] : $userInfo['phone']) ?: ''), // 默认昵称
            'phone' => $userInfo['phone'] ?: '',
            'email' => $userInfo['email'] ?: '',
            'create_time' => $userInfo['create_time'] ? date('Y-m-d H:i:s', $userInfo['create_time']) : '',
            'sex' => $userInfo['sex'],
            'birth' => $userInfo['birth'],
            // 会员卡信息
            'once_nums' => $userInfo['once_nums'],
            'month_day' => $userInfo['month_day'],
            'works_once_nums' => $userInfo['works_once_nums'],
            'works_month_nums' => $userInfo['works_month_nums'],
            'emotion_once_nums' => $userInfo['emotion_once_nums'],
            'emotion_month_nums' => $userInfo['emotion_month_nums'],
            'pr_once_nums' => $userInfo['pr_once_nums'],
            'pr_month_nums' => $userInfo['pr_month_nums'],
            'group_once_nums' => $userInfo['group_once_nums'],
            'group_month_nums' => $userInfo['group_month_nums'],
            'stu_once_nums' => $userInfo['stu_once_nums'],
            'stu_month_nums' => $userInfo['stu_month_nums'],
            'medical_once_nums' => $userInfo['medical_once_nums'],
        ];

        $result = [
            'code' => 0,
            'msg' => Lang::get('get_user_info_success'),
            'data' => $data,
        ];

        return json($result);
    }

    /**
     * 重置密码
     */
    public function resetPassword()
    {
        $result = [
            'code' => 1,
            'msg' => Lang::get('reset_password_failed'),
            'data' => [],
        ];

        // 获取请求参数
        $account = input('post.account'); // 手机号或邮箱
        $code = input('post.code'); // 验证码
        $password = input('post.password'); // 新密码

        // 验证参数
        if (empty($account)) {
            $result['msg'] = Lang::get('account_cannot_be_empty');

            return json($result);
        }

        if (empty($code)) {
            $result['msg'] = Lang::get('captcha_cannot_be_empty');

            return json($result);
        }

        if (empty($password)) {
            $result['msg'] = Lang::get('password_cannot_be_empty');

            return json($result);
        }

        if (strlen($password) < 6) {
            $result['msg'] = Lang::get('password_length_min_6');

            return json($result);
        }

        // 查询用户信息
        $where = [];
        if (preg_match('/^1[3-9]\d{9}$/', $account)) {
            // 手机号
            $where['phone'] = $account;
        } elseif (filter_var($account, FILTER_VALIDATE_EMAIL)) {
            // 邮箱
            $where['email'] = $account;
        } else {
            $result['msg'] = Lang::get('account_format_incorrect');

            return json($result);
        }

        $userInfo = db('member')->where($where)->find();
        if (empty($userInfo)) {
            $result['msg'] = Lang::get('account_not_exist');

            return json($result);
        }

        // 验证验证码
        // 实际项目中应从缓存或数据库中验证验证码是否正确
        // 这里简化处理，假设验证码正确

        // 更新密码
        $updateData = [
            'password' => password_hash($password, PASSWORD_DEFAULT),
        ];

        $updateResult = db('member')->where('id', $userInfo['id'])->update($updateData);
        if ($updateResult === false) {
            $result['msg'] = Lang::get('reset_password_failed_retry');

            return json($result);
        }

        $result = [
            'code' => 0,
            'msg' => Lang::get('reset_password_success'),
            'data' => [],
        ];

        return json($result);
    }

    /**
     * 绑定手机号.
     */
    public function bindPhone()
    {
        $result = [
            'code' => 1,
            'msg' => Lang::get('bind_phone_failed'),
            'data' => [],
        ];

        // 获取当前登录用户ID
        $userId = getUserId();
        if (empty($userId)) {
            $result['msg'] = Lang::get('user_not_logged_in');
            $result['code'] = 401;

            return json($result);
        }

        // 获取请求参数
        $phone = input('post.phone');
        $code = input('post.code');

        // 验证参数
        if (empty($phone) || !preg_match('/^1[3-9]\d{9}$/', $phone)) {
            $result['msg'] = Lang::get('phone_format_incorrect');

            return json($result);
        }

        if (empty($code)) {
            $result['msg'] = Lang::get('captcha_cannot_be_empty');

            return json($result);
        }

        // 验证手机号是否已被绑定
        $existUser = db('member')->where('phone', $phone)->where('id', '<>', $userId)->find();
        if ($existUser) {
            $result['msg'] = Lang::get('phone_already_bound');

            return json($result);
        }

        // 验证验证码
        // 实际项目中应从缓存或数据库中验证验证码是否正确
        // 这里简化处理，假设验证码正确

        // 更新用户手机号
        $result = db('member')->where('id', $userId)->update(['phone' => $phone]);
        if ($result === false) {
            $result = [
                'code' => 1,
                'msg' => Lang::get('bind_phone_failed_retry'),
                'data' => [],
            ];

            return json($result);
        }

        $result = [
            'code' => 0,
            'msg' => Lang::get('bind_phone_success'),
            'data' => [],
        ];

        return json($result);
    }

    /**
     * 绑定邮箱.
     */
    public function bindEmail()
    {
        $result = [
            'code' => 1,
            'msg' => Lang::get('bind_email_failed'),
            'data' => [],
        ];

        // 获取当前登录用户ID
        $userId = getUserId();
        if (empty($userId)) {
            $result['msg'] = Lang::get('user_not_logged_in');
            $result['code'] = 401;

            return json($result);
        }

        // 获取请求参数
        $email = input('post.email');
        $code = input('post.code');

        // 验证参数
        if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $result['msg'] = Lang::get('email_format_incorrect');

            return json($result);
        }

        if (empty($code)) {
            $result['msg'] = Lang::get('captcha_cannot_be_empty');

            return json($result);
        }

        // 验证邮箱是否已被绑定
        $existUser = db('member')->where('email', $email)->where('id', '<>', $userId)->find();
        if ($existUser) {
            $result['msg'] = Lang::get('email_already_bound');

            return json($result);
        }

        // 验证验证码
        // 实际项目中应从缓存或数据库中验证验证码是否正确
        // 这里简化处理，假设验证码正确

        // 更新用户邮箱
        $updateResult = db('member')->where('id', $userId)->update(['email' => $email]);
        if ($updateResult === false) {
            $result = [
                'code' => 1,
                'msg' => Lang::get('bind_email_failed_retry'),
                'data' => [],
            ];

            return json($result);
        }

        $result = [
            'code' => 0,
            'msg' => Lang::get('bind_email_success'),
            'data' => [],
        ];

        return json($result);
    }

    /**
     * 修改手机号.
     */
    public function changePhone()
    {
        $result = [
            'code' => 0,
            'msg' => '',
            'data' => [],
        ];

        return json($result);
    }

    /**
     * 修改邮箱.
     */
    public function changeEmail()
    {
        $result = [
            'code' => 0,
            'msg' => '',
            'data' => [],
        ];

        return json($result);
    }

    /**
     * 修改密码.
     */
    public function changePassword()
    {
        $result = [
            'code' => 1,
            'msg' => Lang::get('change_password_failed'),
            'data' => [],
        ];

        // 获取当前登录用户ID
        $userId = getUserId();
        if (empty($userId)) {
            $result['msg'] = Lang::get('user_not_logged_in');
            $result['code'] = 401;

            return json($result);
        }

        // 获取请求参数
        $newPassword = input('post.new_password');

        if (empty($newPassword)) {
            $result['msg'] = Lang::get('new_password_cannot_be_empty');

            return json($result);
        }

        if (strlen($newPassword) < 6) {
            $result['msg'] = Lang::get('new_password_length_min_6');

            return json($result);
        }

        // 查询用户信息
        $userInfo = db('member')->where('id', $userId)->find();
        if (empty($userInfo)) {
            $result['msg'] = '用户不存在';

            return json($result);
        }

        // 更新密码
        $updateData = [
            'password' => password_hash($newPassword, PASSWORD_DEFAULT),
        ];

        $updateResult = db('member')->where('id', $userId)->update($updateData);
        if ($updateResult === false) {
            $result['msg'] = Lang::get('change_password_failed_retry');

            return json($result);
        }

        $result = [
            'code' => 0,
            'msg' => Lang::get('change_password_success'),
            'data' => [],
        ];

        return json($result);
    }

    /**
     * 获取用户询问历史列表.
     */
    public function history()
    {
        $result = [
            'code' => 1,
            'msg' => Lang::get('get_history_failed'),
            'data' => [],
        ];

        // 获取当前登录用户ID
        $userId = getUserId();
        if (empty($userId)) {
            $result['msg'] = Lang::get('user_not_logged_in');
            $result['code'] = 401;

            return json($result);
        }

        // 获取用户手机号
        $userInfo = db('member')->where('id', $userId)->find();
        if (empty($userInfo)) {
            $result['msg'] = Lang::get('user_not_exist');

            return json($result);
        }

        // 获取请求参数
        $page = input('post.page', 1, 'intval');
        $pageSize = input('post.page_size', 10, 'intval');
        $title = input('post.title', '');

        // 咨询配置
        $personConf = config('personal_consult_tmpl');

        // 构建查询条件
        $condition = [
            'pid' => 0, // 股票自动提问的子区间 子栏目不展示
        ];

        $userIdentifiers = array_filter([
            (string) $userId,
            isset($userInfo['phone']) ? $userInfo['phone'] : '',
        ], function ($value) {
            return $value !== '' && $value !== null;
        });
        $userIdentifiers = array_values(array_unique($userIdentifiers));
        if (empty($userIdentifiers)) {
            $userIdentifiers[] = (string) $userId;
        }

        // 查询历史记录
        $query = db('new_user_question_history')
            ->whereIn('user_phone', $userIdentifiers)
            ->where($condition)
            ->where('user_phone', '<>', '');

        if (!empty($title)) {
            $query = $query->where('person_fix_msg', 'like', '%'.$title.'%');
        }

        $query = $query->order('id', 'desc');

        // 分页查询
        $lists = $query->paginate($pageSize, false, ['page' => $page]);

        $resultList = [];
        if (!empty($lists->items())) {
            foreach ($lists->items() as $k => $row) {
                if (in_array($row['person_menu_id'], [1, 2, 3, 4])) {
                    $types = $row['person_menu_id'];
                    $itypes = $row['person_menu_item_id'];

                    $msgTmpl = isset($personConf[$types]['items'][$itypes]) ? $personConf[$types]['items'][$itypes] : '';
                    if (empty($msgTmpl)) {
                        $msgTitle = $personConf[$types]['title'];
                    } else {
                        // 如果是, 工作事业选择>>第一条
                        if ($itypes == 4) {
                            $msgTitle = sprintf($msgTmpl, $row['person_fix_msg'], $row['person_job']);
                        } else {
                            $msgTitle = sprintf($msgTmpl, $row['person_fix_msg']);
                        }
                    }
                } else {
                    $msgTitle = $row['person_fix_msg'];
                }

                // 获取esey值
                // 这里不调用getcurl方法，直接使用数据库中的值
                $row['msg_title'] = $msgTitle;
                $row['history_id'] = $row['id'];

                // 确保add_time是有效的时间戳
                $timestamp = is_numeric($row['add_time']) ? intval($row['add_time']) : strtotime($row['add_time']);
                if ($timestamp === false) {
                    $timestamp = time(); // 如果转换失败，使用当前时间
                }
                $row['id'] = date('YmdHis', $timestamp).$row['id'];

                $resultList[] = $row;
            }
        }

        // 返回结果
        $result = [
            'code' => 0,
            'msg' => '获取询问历史成功',
            'data' => [
                'total' => $lists->total(),
                'per_page' => $pageSize,
                'current_page' => $page,
                'last_page' => ceil($lists->total() / $pageSize),
                'data' => $resultList,
            ],
        ];

        return json($result);
    }

    /**
     * 获取询问历史详情.
     */

    /**
     * 获取询问历史详情.
     *
     * @return void
     */
    public function historyDetail()
    {
        $result = [
            'code' => 1,
            'msg' => '获取历史详情失败',
            'data' => [],
        ];

        try {
            // 获取当前登录用户ID
            $userId = getUserId();
            if (empty($userId)) {
                $result['msg'] = '用户未登录';
                $result['code'] = 401;

                return json($result);
            }

            // 获取请求参数
            $historyId = input('post.history_id', 0, 'intval');
            // 是否隐藏其他选项 默认 1 显示  2 隐藏
            $isHidden = input('isHidden', '2');
            // 是否是ios  1 是 0 否
            $isIos = input('isIos', 0);
            $flag = input('flag', 0); // 是否记录缓存的标志

            if (empty($historyId)) {
                $result['msg'] = '参数错误';

                return json($result);
            }

            // 查询历史详情
            $historyInfo = db('new_user_question_history')->where('id', $historyId)->find();
            if (empty($historyInfo)) {
                $result['msg'] = '历史记录不存在';

                return json($result);
            }

            // 查询用户信息，验证是否为当前用户的记录
            $userInfo = db('member')->where('id', $userId)->find();
            $allowedIdentifiers = [(string) $userId];
            if (!empty($userInfo['phone'])) {
                $allowedIdentifiers[] = $userInfo['phone'];
            }
            $allowedIdentifiers = array_values(array_unique($allowedIdentifiers));

            if (empty($userInfo) || !in_array($historyInfo['user_phone'], $allowedIdentifiers, true)) {
                $result['msg'] = '无权查看该记录';

                return json($result);
            }

            // 特殊处理：体质查询(99)和症状查询(98) - 根据保存的参数重新查询
            if (in_array($historyInfo['result_type'], [99, 98])) {
                $inputData = json_decode($historyInfo['input_data'], true);
                $queryResult = [];
                
                try {
                    // 体质查询：根据保存的参数重新查询
                    if ($historyInfo['result_type'] == 99) {
                        $birthDate = $inputData['birthDate'];
                        $birthTimeIndex = $inputData['birthTime'];
                        $birthPlace = $inputData['birthPlace'];
                        $isPredict = isset($inputData['predictFuture']) ? $inputData['predictFuture'] : false;
                        
                        // 调用 Index 控制器的查询逻辑
                        $indexController = new \app\v6\controller\Index();
                        
                        // 获取区域信息
                        $areaInfo = $indexController->appService::getAreaInfo();
                        $birthPlaceDescription = '';
                        foreach ($areaInfo as $section => $rowData) {
                            if (in_array($birthPlace, $rowData['areas'])) {
                                $birthPlaceDescription = $rowData['description'];
                                break;
                            }
                        }
                        
                        // 获取年尾数
                        $yearStand = $indexController->appService::getYearEndStand();
                        $yearEnd = substr(substr($birthDate, 0, 4), 3, 1);
                        $monthEnd = substr($birthDate, 5, 2);
                        $dayEnd = substr($birthDate, 8, 2);
                        
                        // 获取生肖信息
                        $animalInfo = $indexController->_birthday($birthDate);
                        $predictInfo = $indexController->_getInfoByAnimal($animalInfo['animal']);
                        $monthAndDayInfo = $indexController->_getTizhiByMonthAndDay($monthEnd, $dayEnd);
                        $birthTimeStand = $indexController->appService::getBirthTimeStand();
                        
                        // 预测信息
                        $predictRes = [];
                        if ($isPredict) {
                            $predictRes = $indexController->getPredictTizhiSearch($animalInfo);
                        }
                        
                        // 五运六气 - 使用 getYearFullInfo 获取完整信息（包括所有时段和特殊年份）
                        $wuyunLiuqi = new \app\service\WuyunLiuqi();
                        $wuyunLiuqiResult = $wuyunLiuqi->getYearFullInfo($birthDate);
                        
                        // 调试日志
                        \think\facade\Log::info('历史详情-五运六气查询结果', [
                            'birthDate' => $birthDate,
                            'has_all_special_years' => isset($wuyunLiuqiResult['all_special_years']),
                            'has_all_periods' => isset($wuyunLiuqiResult['all_periods']),
                            'result_keys' => array_keys($wuyunLiuqiResult)
                        ]);
                        
                        $queryResult = [
                            'year_end' => $yearStand[$yearEnd],
                            'zodiac' => $predictInfo['hot_or_cold'],
                            'animal_ill' => $predictInfo['animal_ill'],
                            'month_day' => $monthAndDayInfo,
                            'detail_time' => $birthTimeStand[$birthTimeIndex],
                            'birth_place_description' => $birthPlaceDescription,
                            'predict_res' => $predictRes,
                            'wuyun_liuqi' => $wuyunLiuqiResult,
                        ];
                    }
                    
                    // 症状查询：根据症状ID重新查询
                    if ($historyInfo['result_type'] == 98) {
                        $symptomDesc = $inputData['symptom_desc'];
                        
                        // 调用 Symptom 控制器的查询逻辑
                        $symptomController = new \app\v6\controller\Symptom();
                        $queryResult = $symptomController->findFormulasBySymptomIds($symptomDesc);
                    }
                } catch (\Exception $e) {
                    $queryResult = [
                        'error' => '重新查询失败: ' . $e->getMessage(),
                        'params' => $inputData
                    ];
                }
                
                $result = [
                    'code' => 0,
                    'msg' => '获取历史详情成功',
                    'data' => [
                        'id' => $historyInfo['id'],
                        'question_msg' => $historyInfo['person_fix_msg'],
                        'result_type' => $historyInfo['result_type'],
                        'add_time' => $historyInfo['add_time'],
                        'input_data' => $inputData,
                        'result' => $queryResult
                    ]
                ];
                
                return json($result);
            }

            $phone = $historyInfo['user_phone'];

            // 根据 historyId 获取相关数据
            $meResultId = $historyInfo['result_id'];
            $taResultId = $historyInfo['ta_result_id'];
            // 用户提问信息
            $personTpl = $historyInfo['person_fix_msg'];

            $type = $historyInfo['person_menu_id'];
            $table = 'docs_latest'; // 项目预测
            if ($type == '2' || $type == '8' || $type == '20') {
                $table = 'docs_works'; // 工作事业
            }
            if ($type == '3' || $type == '9') {
                $table = 'docs_emotion'; // 情感
            }
            if ($type == '19') {
                $table = 'health'; // 健康预测
            }

            $infoMe = db($table)->field('*')->where(['id' => $meResultId])->find();
            $infoTa = db($table)->field('*')->where(['id' => $taResultId])->find();

            if (empty($infoMe) || empty($infoTa)) {
                $result['msg'] = '未查询到咨询结果!';

                return json($result);
            }

            $num_sn = $infoMe['num_sn'];

            $me = $num_sn[7] > 3 ? $num_sn[1] : $num_sn[0];
            $ta = $num_sn[7] > 3 ? $num_sn[0] : $num_sn[1];

            // 使用me的编号进行预测
            if (!empty($historyInfo['me_name']) && empty($historyInfo['ta_name'])) {
                $tmp = $ta;
                $ta = $me;
                $me = $tmp;
            }

            // 处理历史详情数据
            $data = [
            'id' => $historyInfo['id'],
            'num_sn' => $historyInfo['num_sn'] ?: '',
            'question_id' => $historyInfo['question_id'],
            'question_msg' => $historyInfo['person_fix_msg'],
            'date1' => $historyInfo['date1'] ?: '',
            'is_get_profit' => $historyInfo['is_get_profit'] ?: '',
            'me_wants' => $historyInfo['me_wants'] ?: '',
            'ta_idea' => $historyInfo['ta_idea'] ?: '',
            'startenddate' => $historyInfo['startenddate'] ?: '',
            'health_status' => $historyInfo['health_status'] ?: '',
            'year_good' => $historyInfo['year_good'] ?: '',
            'month_good' => $historyInfo['month_good'] ?: '',
            'day_good' => $historyInfo['day_good'] ?: '',
            'date_diff' => $historyInfo['date_diff'] ?: '',
            'is_special' => $historyInfo['is_special'],
            'hui' => $historyInfo['hui'],
            'is_coflict' => $historyInfo['is_coflict'],
            'is_month_coflict' => $historyInfo['is_month_coflict'],
            'is_date_coflict' => $historyInfo['is_date_coflict'],
            'is_second_coflict' => $historyInfo['is_second_coflict'],
            'deal_152232' => $historyInfo['deal_152232'],
            'contact_text' => $historyInfo['contact_text'] ?: '',
            'easy' => $historyInfo['easy'],
            'last_num_text' => $historyInfo['last_num_text'] ?: '',
            'is_special_medical' => $historyInfo['is_special_medical'],
            'ta_idea_list' => json_decode($historyInfo['ta_idea_list'], true) ?: [],
            'me_xintai' => $historyInfo['me_xintai'] ?: '',
            'things_degree' => $historyInfo['things_degree'] ?: '',
            'me_xinli' => $historyInfo['me_xinli'] ?: '',
            'contact' => $historyInfo['contact'],
            'result_title' => json_decode($historyInfo['result_title'], true) ?: [],
            'resolve_pay' => $historyInfo['resolve_pay'],
            'solution' => $historyInfo['solution'] ?: '',
            'qrcode' => $historyInfo['qrcode'] ?: '',
        ];

            // 返回结果
            $result = [
                'code' => 0,
                'msg' => '获取历史详情成功',
                'data' => $data,
            ];

            return json($result);
        } catch (\Throwable $th) {
            $result['code'] = 1;
            $result['msg'] = $th->getMessage();

            return json($result);
        }
    }
}
